// 死锁————尝试不同线程之间能否解锁

#include <iostream>
#include <pthread.h>
#include <unistd.h>

using namespace std;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;      // 全局初始化锁

void* threadRoutine(void* args)
{
    cout << "I an a new thread" << endl;

    pthread_mutex_lock(&mutex);

    cout << "I got a mutex" << endl;

    pthread_mutex_lock(&mutex);     // 死锁，两次申请同一把锁，会阻塞

    cout << "I alive again" << endl;

    return nullptr;
}

int main()
{
    // 创建一个线程
    pthread_t tid;
    pthread_create(&tid, nullptr, threadRoutine, nullptr);
    
    // 模拟主线程等待子线程阻塞后再运行
    sleep(3);

    cout << "main thread run begin" << endl;
    pthread_mutex_unlock(&mutex);   // 尝试解锁另一个线程中的锁
    cout << "main thread unlock" << endl;

    sleep(3);

    return 0;
}